package main

import (
	"github.com/PuerkitoBio/goquery"
	"golang.org/x/net/html"
	"log"
	"strings"
)

func main() {
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(`<goods class="xxx-ams-item xxx-ams-goods" data-id="50" data-name="慧殿堂合金工程车G60-4轻型挖掘机（D）"></goods>
<p>测试一下</p>
<coupon class="xxx-ams-item xxx-ams-goods" data-id="50" data-name="慧殿堂合金工程车G60-4轻型挖掘机（D）"></coupon><p><br></p><goods class="kidswant-ams-item kidswant-ams-goods" data-id="50" data-name="慧殿堂合金工程车G60-4轻型挖掘机（D）"></goods><br><br><br><p><img src="http://amspic-10003009.image.myqcloud.com/3c4d7510-78be-4955-9fbd-42f7c9bcb9eb" alt="深度截图_选择区域_20180504153401" style="max-width:100%;"></p><p><br></p>`))
	if err != nil {
		log.Fatal(err)
	}
	body := doc.Find("body")
	children := body.Children()
	childNodes := goquery.NewDocumentFromNode(new(html.Node))
	var result []string
	for i := 0; i < children.Length(); i++ {
		child := children.Get(i)
		switch child.Data {
		case "goods":
			if childNodes.Nodes[0].FirstChild != nil {
				textstr, _ := childNodes.Html()
				result = append(result, textstr)
				childNodes = goquery.NewDocumentFromNode(new(html.Node))
			}
			childNodes.AppendNodes(child)
			goodsstr, _ := childNodes.Html()
			result = append(result, goodsstr)
			childNodes = goquery.NewDocumentFromNode(new(html.Node))
		case "coupon":
			if childNodes.Nodes[0].FirstChild != nil {
				textstr, _ := childNodes.Html()
				result = append(result, textstr)
				childNodes = goquery.NewDocumentFromNode(new(html.Node))
			}
			childNodes.AppendNodes(child)
			goodsstr, _ := childNodes.Html()
			result = append(result, goodsstr)
			childNodes = goquery.NewDocumentFromNode(new(html.Node))
		default:
			childNodes.AppendNodes(child)
		}
		if childNodes.Nodes[0].FirstChild != nil {
			textstr, _ := childNodes.Html()
			result = append(result, textstr)
		}
	}
	log.Println(result)
}
